<template>
  <div class="checkin-card" :class="{ 'checked-in': isCheckedIn }">
    <!-- 签到卡片主体 -->
    <div class="card-header">
      <div class="header-left">
        <CalendarOutlined class="calendar-icon" />
        <span class="title">每日签到</span>
      </div>
      <div class="header-right">
        <a-button
          type="primary"
          size="small"
          :disabled="isCheckedIn"
          @click="handleCheckin"
          :loading="checkinLoading"
          class="checkin-btn"
        >
          <template #icon>
            <CheckCircleOutlined v-if="isCheckedIn" />
            <ClockCircleOutlined v-else />
          </template>
          {{ isCheckedIn ? '已签到' : '立即签到' }}
        </a-button>
      </div>
    </div>

    <!-- 连续签到信息 -->
    <div class="streak-info">
      <div class="streak-days">
        <span class="days-number">{{ continuousDays }}</span>
        <span class="days-label">连续签到</span>
      </div>
      <div class="streak-progress">
        <a-progress
          :percent="streakProgress"
          :show-info="false"
          :stroke-color="streakColor"
          size="small"
        />
        <span class="progress-text">距离下次奖励还需 {{ nextRewardDays }} 天</span>
      </div>
    </div>

    <!-- 今日奖励 -->
    <div v-if="todayReward" class="today-reward">
      <GiftOutlined class="reward-icon" />
      <span class="reward-text">今日奖励：{{ todayReward }}</span>
    </div>

    <!-- 签到日历 -->
    <div class="calendar-section">
      <div class="calendar-header">
        <span class="calendar-title">本月签到</span>
        <a-button type="link" size="small" @click="showCheckinModal"> 查看详情 </a-button>
      </div>
      <div class="calendar-grid">
        <div
          v-for="day in calendarDays"
          :key="day.date"
          class="calendar-day"
          :class="{
            checked: day.checked,
            today: day.isToday,
            future: day.isFuture,
          }"
        >
          <span class="day-number">{{ day.dayNumber }}</span>
          <CheckCircleOutlined v-if="day.checked" class="check-icon" />
        </div>
      </div>
    </div>

    <!-- 签到统计 -->
    <div class="stats-section">
      <div class="stat-item">
        <span class="stat-label">本月签到</span>
        <span class="stat-value">{{ monthlyCheckins }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">总签到天数</span>
        <span class="stat-value">{{ totalCheckins }}</span>
      </div>
      <div class="stat-item">
        <span class="stat-label">最长连续</span>
        <span class="stat-value">{{ maxStreak }}</span>
      </div>
    </div>
  </div>

  <!-- 签到详情模态框 -->
  <a-modal v-model:open="checkinModalVisible" title="签到详情" width="800px" :footer="null">
    <div class="checkin-detail-placeholder">
      <p>签到详情功能开发中...</p>
      <p>总签到天数: {{ totalCheckins }}</p>
      <p>连续签到天数: {{ continuousDays }}</p>
      <p>最长连续天数: {{ maxStreak }}</p>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, watch } from 'vue'
  import { message } from 'ant-design-vue'
  import {
    CalendarOutlined,
    CheckCircleOutlined,
    ClockCircleOutlined,
    GiftOutlined,
  } from '@ant-design/icons-vue'
  import {
    userCheckinUsingPost,
    getUserCheckinInfoUsingGet,
    getUserCheckinRecordsUsingGet,
    getCheckinRewardsUsingGet,
  } from '@/api/yonghumokuaijiekou'
  import { useLoginUserStore } from '@/stores/useLoginUserStore'
  // import CheckinDetailModal from './CheckinDetailModal.vue'

  // 状态管理
  const loginUserStore = useLoginUserStore()

  // 响应式数据
  const checkinLoading = ref(false)
  const checkinModalVisible = ref(false)
  const isCheckedIn = ref(false)
  const continuousDays = ref(0)
  const monthlyCheckins = ref(0)
  const totalCheckins = ref(0)
  const maxStreak = ref(0)
  const todayReward = ref('')
  const nextRewardDays = ref(0)

  // 签到信息
  const checkinInfo = ref<any>({})
  const checkinRecords = ref<any[]>([])
  const rewardsConfig = ref<any[]>([])

  // 计算属性
  const streakProgress = computed(() => {
    const nextReward = rewardsConfig.value.find(reward => reward.days > continuousDays.value)
    if (!nextReward) return 100
    return Math.min((continuousDays.value / nextReward.days) * 100, 100)
  })

  const streakColor = computed(() => {
    if (continuousDays.value >= 30) return '#52c41a'
    if (continuousDays.value >= 7) return '#1890ff'
    return '#faad14'
  })

  // 日历数据
  const calendarDays = computed(() => {
    const today = new Date()
    const year = today.getFullYear()
    const month = today.getMonth()
    const daysInMonth = new Date(year, month + 1, 0).getDate()
    const firstDay = new Date(year, month, 1).getDay()

    const days = []

    // 填充上个月的日期
    for (let i = 0; i < firstDay; i++) {
      days.push({
        date: '',
        dayNumber: '',
        checked: false,
        isToday: false,
        isFuture: false,
      })
    }

    // 填充当前月的日期
    for (let i = 1; i <= daysInMonth; i++) {
      const date = new Date(year, month, i)
      const isToday = i === today.getDate()
      const isFuture = date > today

      days.push({
        date: `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`,
        dayNumber: i,
        checked: checkinRecords.value.some(
          record =>
            record.checkinDate ===
            `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`
        ),
        isToday,
        isFuture,
      })
    }

    return days
  })

  // 获取签到信息
  const fetchCheckinInfo = async () => {
    try {
      const res = await getUserCheckinInfoUsingGet()
      if (res.data.code === 200 && res.data.data) {
        const data = res.data.data
        isCheckedIn.value = data.todayChecked || false
        continuousDays.value = data.continuousDays || 0
        monthlyCheckins.value = data.monthlyCheckins || 0
        totalCheckins.value = data.totalCheckins || 0
        maxStreak.value = data.maxStreak || 0
        checkinInfo.value = data
      }
    } catch (error) {
      console.error('获取签到信息失败:', error)
    }
  }

  // 获取签到记录
  const fetchCheckinRecords = async () => {
    try {
      const today = new Date()
      const startDate = new Date(today.getFullYear(), today.getMonth(), 1)
      const endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0)

      const res = await getUserCheckinRecordsUsingGet({
        startDate: startDate.toISOString().split('T')[0],
        endDate: endDate.toISOString().split('T')[0],
        page: 1,
        pageSize: 100,
      })

      if (res.data.code === 200 && res.data.data && Array.isArray(res.data.data.records)) {
        checkinRecords.value = res.data.data.records
      }
    } catch (error) {
      console.error('获取签到记录失败:', error)
    }
  }

  // 获取奖励配置
  const fetchRewardsConfig = async () => {
    try {
      const res = await getCheckinRewardsUsingGet()
      if (res.data.code === 200) {
        rewardsConfig.value = res.data.data || []

        // 计算今日奖励和下次奖励
        const todayConfig = rewardsConfig.value.find(
          reward => reward.days === continuousDays.value + 1
        )
        if (todayConfig) {
          todayReward.value = todayConfig.reward
        }

        const nextReward = rewardsConfig.value.find(reward => reward.days > continuousDays.value)
        if (nextReward) {
          nextRewardDays.value = nextReward.days - continuousDays.value
        }
      }
    } catch (error) {
      console.error('获取奖励配置失败:', error)
    }
  }

  // 处理签到
  const handleCheckin = async () => {
    if (!loginUserStore.loginUser?.id) {
      message.warning('请先登录')
      return
    }

    checkinLoading.value = true
    try {
      const res = await userCheckinUsingPost()
      if (res.data.code === 200) {
        message.success('签到成功！')
        isCheckedIn.value = true
        continuousDays.value += 1
        monthlyCheckins.value += 1
        totalCheckins.value += 1

        // 重新获取数据
        await Promise.all([fetchCheckinInfo(), fetchCheckinRecords(), fetchRewardsConfig()])
      } else {
        message.error(res.data.message || '签到失败')
      }
    } catch (error) {
      console.error('签到失败:', error)
      message.error('签到失败，请稍后重试')
    } finally {
      checkinLoading.value = false
    }
  }

  // 显示签到详情
  const showCheckinModal = () => {
    checkinModalVisible.value = true
  }

  // 监听用户登录状态
  watch(
    () => loginUserStore.loginUser?.id,
    newId => {
      if (newId) {
        fetchCheckinInfo()
        fetchCheckinRecords()
        fetchRewardsConfig()
      }
    }
  )

  // 生命周期
  onMounted(() => {
    if (loginUserStore.loginUser?.id) {
      fetchCheckinInfo()
      fetchCheckinRecords()
      fetchRewardsConfig()
    }
  })
</script>

<style scoped>
  .checkin-card {
    background: linear-gradient(135deg, var(--theme-primary) 0%, var(--theme-secondary) 100%);
    border-radius: 16px;
    padding: 20px;
    color: var(--theme-surface);
    box-shadow: 0 8px 32px var(--theme-shadow);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
  }

  .checkin-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="stars" patternUnits="userSpaceOnUse" width="20" height="20"><circle cx="10" cy="10" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23stars)"/></svg>');
    opacity: 0.3;
  }

  .checkin-card.checked-in {
    background: linear-gradient(135deg, var(--theme-success) 0%, var(--theme-warning) 100%);
    box-shadow: 0 8px 32px var(--theme-shadow);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    position: relative;
    z-index: 1;
  }

  .header-left {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .calendar-icon {
    font-size: 20px;
    color: var(--theme-warning);
  }

  .title {
    font-size: 18px;
    font-weight: 600;
  }

  .checkin-btn {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    backdrop-filter: blur(10px);
  }

  .checkin-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.5);
  }

  .streak-info {
    margin-bottom: 16px;
    position: relative;
    z-index: 1;
  }

  .streak-days {
    display: flex;
    align-items: baseline;
    gap: 8px;
    margin-bottom: 8px;
  }

  .days-number {
    font-size: 32px;
    font-weight: bold;
    color: var(--theme-warning);
  }

  .days-label {
    font-size: 14px;
    opacity: 0.8;
  }

  .streak-progress {
    margin-top: 8px;
  }

  .progress-text {
    font-size: 12px;
    opacity: 0.8;
    margin-top: 4px;
    display: block;
  }

  .today-reward {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    padding: 8px 12px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
    position: relative;
    z-index: 1;
  }

  .reward-icon {
    color: var(--theme-warning);
    font-size: 16px;
  }

  .reward-text {
    font-size: 14px;
    font-weight: 500;
  }

  .calendar-section {
    margin-bottom: 16px;
    position: relative;
    z-index: 1;
  }

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .calendar-title {
    font-size: 14px;
    font-weight: 500;
  }

  .calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 4px;
  }

  .calendar-day {
    aspect-ratio: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 6px;
    position: relative;
    font-size: 12px;
  }

  .calendar-day.checked {
    background: rgba(82, 196, 26, 0.3);
    border: 1px solid rgba(82, 196, 26, 0.5);
  }

  .calendar-day.today {
    background: rgba(255, 215, 0, 0.3);
    border: 1px solid rgba(255, 215, 0, 0.5);
  }

  .calendar-day.future {
    opacity: 0.5;
  }

  .check-icon {
    position: absolute;
    top: 2px;
    right: 2px;
    font-size: 8px;
    color: #52c41a;
  }

  .stats-section {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    position: relative;
    z-index: 1;
  }

  .stat-item {
    text-align: center;
    padding: 8px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 8px;
  }

  .stat-label {
    display: block;
    font-size: 12px;
    opacity: 0.8;
    margin-bottom: 4px;
  }

  .stat-value {
    display: block;
    font-size: 18px;
    font-weight: bold;
    color: var(--theme-warning);
  }

  .checkin-detail-placeholder {
    padding: 20px;
    text-align: center;
    color: #666;
  }

  .checkin-detail-placeholder p {
    margin: 8px 0;
    font-size: 14px;
  }

  @media (max-width: 768px) {
    .checkin-card {
      padding: 16px;
    }

    .days-number {
      font-size: 24px;
    }

    .calendar-grid {
      gap: 2px;
    }

    .calendar-day {
      font-size: 10px;
    }

    .stats-section {
      grid-template-columns: repeat(3, 1fr);
      gap: 8px;
    }
  }
</style>
